package per.hx.bs.sys.serviceimpl;

import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import per.hx.bs.base.domain.Tree;
import per.hx.bs.sys.dao.SysMenuDao;
import per.hx.bs.sys.dao.SysRoleMenuDao;
import per.hx.bs.entity.sys.SysMenuDO;
import per.hx.bs.util.BuildTree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HuXing
 * @date 2018/3/21  21:59
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping(value = "sys-service/menu")
public class SysMenuApiServiceImpl {


    private final
    SysMenuDao sysMenuDao;
    private final
    SysRoleMenuDao sysRoleMenuDao;

    @Autowired
    public SysMenuApiServiceImpl(SysMenuDao sysMenuDao, SysRoleMenuDao sysRoleMenuDao) {
        this.sysMenuDao = sysMenuDao;
        this.sysRoleMenuDao = sysRoleMenuDao;
    }

    /**
     * 获取用户对应菜单
     *
     * @param userId 用户Id
     * @return 菜单结构
     */
    @GetMapping(value = "/listMenuTree")
    public List<Tree<SysMenuDO>> listMenuTree(@RequestParam("userId") Long userId) {
        List<Tree<SysMenuDO>> trees = new ArrayList<Tree<SysMenuDO>>();
        List<SysMenuDO> menuDOs = sysMenuDao.listMenuByUserId(userId);
        setTree(trees, menuDOs);
        // 默认顶级菜单为０，根据数据库实际情况调整
        return trees;
        //BuildTree.buildList(trees, "0");
    }

    /**
     * 获取菜单列表
     *
     * @param sort 列表参数
     * @return 菜单集合
     */
    @GetMapping(value = "/list")
    public List<SysMenuDO> list(@RequestParam("sort") String sort) {
        Map<String, Object> params = new HashMap<String, Object>(1);
        params.put("sort", sort);
        return sysMenuDao.list(params);
    }

    /**
     * 获取单个菜单项信息
     *
     * @param menuId 菜单Id
     * @return 菜单信息
     */
    @GetMapping(value = "/{menuId}")
    public SysMenuDO getOne(@PathVariable("menuId") Long menuId) {
        return sysMenuDao.selectById(menuId);
    }

    /**
     * 添加菜单
     *
     * @param sysMenuDO 保存的菜单信息
     * @return 影响的行数
     */
    @PostMapping(value = "/save")
    public int save(@RequestBody SysMenuDO sysMenuDO) {
        return sysMenuDao.insert(sysMenuDO);
    }

    /**
     * 修改菜单
     *
     * @param sysMenuDO 更改信息
     * @return 影响的行数
     */
    @PutMapping(value = "/update")
    public int update(@RequestBody SysMenuDO sysMenuDO) {
        return sysMenuDao.updateAllColumnById(sysMenuDO);
    }

    /**
     * 删除菜单
     *
     * @param id id
     * @return 影响的行数
     */
    @DeleteMapping(value = "/remove")
    public int remove(@RequestParam("id") Long id) {
        return sysMenuDao.deleteById(id);
    }

    /**
     * 获取树形菜单
     *
     * @return 获取树形菜单
     */
    @GetMapping(value = "/tree")
    public String getTree() {
        List<Tree<SysMenuDO>> trees = new ArrayList<Tree<SysMenuDO>>();
        List<SysMenuDO> sysMenuDOS = sysMenuDao.selectByMap(new HashMap<String, Object>(5));
        for (SysMenuDO sysMenuDO : sysMenuDOS) {
            Tree<SysMenuDO> tree = new Tree<SysMenuDO>();
            tree.setId(sysMenuDO.getMenuId().toString());
            tree.setParentId(sysMenuDO.getParentId().toString());
            tree.setText(sysMenuDO.getName());
            trees.add(tree);
        }
        return JSON.toJSONString(BuildTree.build(trees, null));
    }

    /**
     * 获取树形菜单
     *
     * @param roleId 角色id
     * @return 获取树形菜单
     */
    @GetMapping(value = "/tree/{roleId}")
    public String getTree(@PathVariable("roleId") Long roleId) {
        // 根据roleId查询权限
        List<SysMenuDO> sysMenuDOS = sysMenuDao.selectByMap(new HashMap<String, Object>(0));
        List<Long> sysMenuIds = sysRoleMenuDao.selectMenuIdByRoleId(roleId);

        for (SysMenuDO sysMenuDO : sysMenuDOS) {
            sysMenuIds.remove(sysMenuDO.getParentId());
        }
        List<Tree<SysMenuDO>> trees = new ArrayList<Tree<SysMenuDO>>();
        List<SysMenuDO> menus = sysMenuDao.selectByMap(new HashMap<String, Object>(0));
        for (SysMenuDO sysMenuDO : menus) {
            Tree<SysMenuDO> tree = new Tree<SysMenuDO>();
            tree.setId(sysMenuDO.getMenuId().toString());
            tree.setParentId(sysMenuDO.getParentId().toString());
            tree.setText(sysMenuDO.getName());
            Map<String, Object> state = new HashMap<String, Object>(1);
            Long menuId = sysMenuDO.getMenuId();
            if (sysMenuIds.contains(menuId)) {
                state.put("selected", true);
            } else {
                state.put("selected", false);
            }
            tree.setState(state);
            trees.add(tree);
        }
        return JSON.toJSONString(BuildTree.build(trees, null));
    }

    /**
     * 通过名称查询 菜单
     *
     * @param name 菜单名称
     * @return 菜单信息
     */
    @GetMapping(value = "/name/{name}")
    public List<SysMenuDO> searchByName(@PathVariable("name") String name) {
        EntityWrapper<SysMenuDO> ew = new EntityWrapper<SysMenuDO>();
        ew.setEntity(new SysMenuDO());
        ew.where("name={0}", name);
        return sysMenuDao.selectList(ew);
    }

    private void setTree(List<Tree<SysMenuDO>> trees, List<SysMenuDO> sysMenuDOS) {
        for (SysMenuDO sysMenuDO : sysMenuDOS) {
            Tree<SysMenuDO> tree = new Tree<SysMenuDO>();
            tree.setId(sysMenuDO.getMenuId().toString());
            tree.setParentId(sysMenuDO.getParentId().toString());
            tree.setText(sysMenuDO.getName());
            Map<String, Object> attributes = new HashMap<String, Object>(16);
            attributes.put("url", sysMenuDO.getUrl());
            attributes.put("icon", sysMenuDO.getIcon());
            tree.setAttributes(attributes);
            trees.add(tree);
        }
    }


}
